/*****************************************************************************
 * 网络营销新平台
 *****************************************************************************
 * HttpsUtil.java
 *----------------------------------------------------------------------------
 * (C) 沈阳八维时空科技发展
 *     SHENYANG EIGHTSPACE TECHNOLOGY DEVELOPMENT CO.,LTD.  2012
 *----------------------------------------------------------------------------
 * Version    Date       By            Comment
 * 1.0        2014-4-2    Frank       新建
 *****************************************************************************/
package net.heartarea.boer.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import net.heartarea.boer.apps.weixin.pojo.MenuBean;

import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.eightspace.server.common.log.LogManagment;

/**
 * FIXME 此处填写类的描述信息
 * 
 * @author Frank
 * @date 2014-4-2
 * @since 1.0
 */
public class HttpsUtil {
    private static final String METHOD_POST = "POST";

    private static final String DEFAULT_CHARSET = "utf-8";

    /**
     * 
     */
    private static LogManagment log = LogManagment.getLogger(HttpsUtil.class);



    public static String doPost(String url, String params, String charset, int connectTimeout, int readTimeout)
        throws Exception {
        String ctype = "application/json;charset=" + charset;
        byte[] content = {};
        if (params != null) {
            content = params.getBytes(charset);
        }

        return doPost(url, ctype, content, connectTimeout, readTimeout);
    }

    private static class DefaultTrustManager implements X509TrustManager {

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }



        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }



        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

    }



    public static String doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout)
        throws Exception {
        HttpsURLConnection conn = null;
        OutputStream out = null;
        String rsp = null;
        try {
            try {
                SSLContext ctx = SSLContext.getInstance("TLS");
                ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
                SSLContext.setDefault(ctx);

                conn = getConnection(new URL(url), METHOD_POST, ctype);
                conn.setHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });
                conn.setConnectTimeout(connectTimeout);
                conn.setReadTimeout(readTimeout);
            } catch (Exception e) {
                log.error("GET_CONNECTOIN_ERROR, URL = " + url, e);
                throw e;
            }
            try {
                out = conn.getOutputStream();
                out.write(content);
                rsp = getResponseAsString(conn);
            } catch (IOException e) {
                log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);
                throw e;
            }

        } finally {
            if (out != null) {
                out.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }

        return rsp;
    }



    private static HttpsURLConnection getConnection(URL url, String method, String ctype) throws IOException {
        HttpsURLConnection conn = ( HttpsURLConnection ) url.openConnection();
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestProperty("Accept", "text/xml,text/javascript,text/html");
        conn.setRequestProperty("User-Agent", "stargate");
        conn.setRequestProperty("Content-Type", ctype);
        return conn;
    }



    protected static String getResponseAsString(HttpURLConnection conn) throws IOException {
        String charset = getResponseCharset(conn.getContentType());
        InputStream es = conn.getErrorStream();
        if (es == null) {
            return getStreamAsString(conn.getInputStream(), charset);
        } else {
            String msg = getStreamAsString(es, charset);
            if (StringUtils.isEmpty(msg)) {
                throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
            } else {
                throw new IOException(msg);
            }
        }
    }



    private static String getStreamAsString(InputStream stream, String charset) throws IOException {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));
            StringWriter writer = new StringWriter();

            char[] chars = new char[256];
            int count = 0;
            while ((count = reader.read(chars)) > 0) {
                writer.write(chars, 0, count);
            }

            return writer.toString();
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    }



    private static String getResponseCharset(String ctype) {
        String charset = DEFAULT_CHARSET;

        if (!StringUtils.isEmpty(ctype)) {
            String[] params = ctype.split(";");
            for (String param : params) {
                param = param.trim();
                if (param.startsWith("charset")) {
                    String[] pair = param.split("=", 2);
                    if (pair.length == 2) {
                        if (!StringUtils.isEmpty(pair[1])) {
                            charset = pair[1].trim();
                        }
                    }
                    break;
                }
            }
        }

        return charset;
    }



    public static void main(String[] args) {
        try {
            String accessToken = "qYT5DDcA0u0TTsVh9AYywdQJQd2idrNQInNcqIUY2HulfVWGXpUMteSTdu4g9nmybR68GZiP93qVWLzc9O3hiR-4QzP2eKsj6CEivQmNenWDvzFCXu-bGOSJ0pUpBYu6pdwHKWn0kNM4T1ZTjQ7THQ";
            String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken;
            Map<String, Object> paramMap = new HashMap<String, Object>();

            List<MenuBean> buttons = new ArrayList<MenuBean>();
            buttons.add(new MenuBean("click", "商业合作", "shangyehezuo", ""));
            buttons.add(new MenuBean("click", "平台简介", "pingtaijianjie", ""));
            buttons.add(new MenuBean("view", "投票", "", "http://www.heartarea.net"));
            paramMap.put("button", buttons);
            String result = doPost(url, JSON.toJSONString(paramMap), DEFAULT_CHARSET, 1200, 1200);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
